<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false">
      </el-alert>
      <el-row class="cat_opt">
        <el-col class="text-bot">
          <p>选择商品分类</p>
        </el-col>
        <!-- 分类的级联选择器 -->
        <el-cascader v-model="selectedCateKeys" :options="cateList" :props="cascaderProps"
        @change="cateCascaderChange"></el-cascader>
      </el-row>
      <!-- tab页签 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isDisabled" @click="addDialog">添加参数</el-button>
          <el-table :data="manyTableData" stripe border>
            <!-- 折叠 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable
                @close="closeTag(i,scope.row)">{{item}}</el-tag>
                <!-- tag标签的按钮与文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作" width="600px">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isDisabled" @click="addDialog">添加属性</el-button>
          <el-table :data="onlyTableData" stripe border>
            <!-- 折叠 -->
            <el-table-column type="expand">
               <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="closeTag(i,scope.row)">{{item}}</el-tag>
                <!-- tag标签的按钮与文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作" width="600px">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数/添加属性对话框 -->
      <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="30%" @close="resetForm">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!--修改参数/属性对话框-->
      <el-dialog :title="'添加'+titleText" :visible.sync="editDialogVisible" width="30%" @close="resetEditForm">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 接收分类列表数据
      cateList: [],
      // 级联选择器配置
      cascaderProps: {
        expandTrigger: 'hover',
        // 指定子树属性名
        children: 'children',
        // 要展示的每一项的值
        label: 'cat_name',
        // 选中项绑定的值，并存储至v-model绑定的属性中
        value: 'cat_id'
      },
      // 级联选择器中选中项绑定的值
      selectedCateKeys: [],
      // tab页签
      activeName: 'many',
      // tab页签数据接收
      manyTableData: [],
      onlyTableData: [],
      // 控制添加参数/属性对话框显示与隐藏
      addDialogVisible: false,
      // 编辑对话框的显示
      editDialogVisible: false,
      // 添加参数/属性的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 编辑对话框的表单数据对象
      editForm: {},
      // 验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      editFormRules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败')
      }
      this.cateList = res.data
    },
    // 级联选择器事件
    cateCascaderChange () {
      console.log(this.selectedCateKeys)
      // 如果选中的不是三级分类则重置级联器
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        // 清空参数列表
        this.manyTableData = []
        this.onlyTableData = []
      }
      // 发起请求
      this.getParamsList()
    },
    // 请求参数列表函数
    async getParamsList () {
      // 发起请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // 将数据中的attr_vals转化成数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 给每行数据添加两个属性用于动态tag标签
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      // 将tab页签中两种情况下获取到的数据挂在到不同的变量中
      // 如果当前tab页签为动态参数
      if (this.activeName === 'many') {
        this.manyTableData = res.data
        console.log(this.manyTableData)
      }
      // 如果当前tab页签为静态参数
      if (this.activeName === 'only') {
        this.onlyTableData = res.data
      }
    },

    // tab页签改变事件
    handleClick () {
      console.log(this.activeName)
      // 发起请求
      this.getParamsList()
    },
    // 添加参数、属性的对话框
    addDialog () {
      this.addDialogVisible = true
    },
    // 重置表单
    resetForm () {
      this.$refs.addFormRef.resetFields()
    },
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    // 提交添加的参数
    addParams () {
      // 表单预校验
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请输入合法名称')
        }
        // 发送请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('创建失败')
        }
        this.getParamsList()
        this.addDialogVisible = false
        this.$message.success('创建成功')
      })
    },
    // 显示编辑框
    async showEditDialog (scopeRow) {
      const attrId = scopeRow.attr_id
      // 发送请求根据id查询参数
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询参数失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 发送请求
    editParams () {
      // 表单预校验
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请输入合法的内容')
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.getParamsList()
        this.editDialogVisible = false
        this.$message.success('修改成功')
      })
    },
    // 删除参数
    async deleteParams (scopeRow) {
      const res = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (res !== 'confirm') {
        return this.$message('取消了删除')
      }
      const attrId = scopeRow.attr_id
      // 发起删除请求
      const { data: params } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      console.log(params)
      if (params.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getParamsList()
      this.$message.success('删除成功')
    },
    // 文本框失去焦点或按下enter键
    async handleInputConfirm (scopeRow) {
      // 输入了空内容
      if (scopeRow.inputValue.trim().length === 0) {
        scopeRow.inputValue = ''
        scopeRow.inputVisible = false
        return
      }
      // 输入了有效内容
      scopeRow.attr_vals.push(scopeRow.inputValue)
      // 重置输入内容
      scopeRow.inputValue = ''
      // 隐藏文本框
      scopeRow.inputVisible = false
      // 提交请求
      this.saveAttrVals(scopeRow)
    },
    // 提交修改了参数的属性值的请求
    async saveAttrVals (scopeRow) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${scopeRow.attr_id}`,
        {
          attr_name: scopeRow.attr_name,
          attr_sel: scopeRow.attr_sel,
          attr_vals: scopeRow.attr_vals.join(' ')
        })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数属性失败')
      }
      this.$message.success('修改参数属性成功')
    },
    // 删除可选项
    closeTag (i, scopeRow) {
      scopeRow.attr_vals.splice(i, 1)
      this.saveAttrVals(scopeRow)
    },
    // 点击按钮转化为文本
    showInput (scopeRow) {
      // 改变为true时文本框并未被渲染出来
      scopeRow.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick()方法的作用：当页面上元素被重新渲染后，才会执行回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 控制按钮是否禁用
    isDisabled () {
      if (this.selectedCateKeys.length === 3) {
        return false
      }
      return true
    },
    // 获取选中的三级分类的id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 控制文本为添加参数/添加属性
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.text-bot {
  margin-bottom: 10px;
}
.el-tabs {
  margin-top: 10px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag{
  width: 120px;
}
</style>
